package com.salefinder.server.server.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.salefinder.server.server.exception.SystemException;
import com.salefinder.server.server.util.Constant;
import com.salefinder.server.server.vo.Brand;
import com.salefinder.server.server.vo.ConsumerProduct;
import com.salefinder.server.server.vo.Location;
import com.salefinder.server.server.vo.Merchant;
import com.salefinder.server.server.vo.Product;

public class ConsumerProductDao extends BaseDao {

	public void createOrUpdateConsumerProduct(ConsumerProduct vo){
		this.createOrUpdate(vo);
	}
	
	public void deleteConsumerProduct(ConsumerProduct vo){
		this.delete(vo);
	}
	
	public ConsumerProduct loadConsumerProduct(ConsumerProduct vo){
		return (ConsumerProduct) this.load(this.getClass(), vo.getId());
	}
	
	public List<ConsumerProduct> searchConsumerProduct(ConsumerProduct vo) throws SystemException{
		List<ConsumerProduct> productList;
		
		try{
			Session session = this.getSessionFactory().openSession();
			
			productList = session.createCriteria(ConsumerProduct.class)
			.createCriteria("products")
			.add(Restrictions.like("name", "%"+ vo.getProduct().getName()+"%"))
			.add(Restrictions.like("brand", "%"+ vo.getBrand()+"%"))
			.add(Restrictions.like("merchant", "%"+ vo.getMerchant()+"%"))
			.addOrder(Order.asc("salePrice"))
		    .list();
	
			session.close();

			}catch(Exception e){
				throw new SystemException(Constant.SYSTEM_ERROR,"System error creating user", e);
			}
			return productList;
	}
	
	public List<String> searchConsumerProductNames(String name, int limit) throws SystemException{
		List<Product> productList;
		List<String> arr;
		try{
			Session session = this.getSessionFactory().openSession();
			
			productList = session.createCriteria(Product.class)
			.add(Restrictions.like("name", name +"%"))
			.addOrder(Order.asc("name"))
			.setMaxResults(limit)
		    .list();
			session.close();
			
			arr = new ArrayList<String>();
			for(int i = 0; i < productList.size(); i++){
				arr.add(productList.get(i).getName());
			}

			}catch(Exception e){
				throw new SystemException(Constant.SYSTEM_ERROR,"System error creating user", e);
			}
			
			return arr;
	}
	

	

}
